import { View, Text, Button } from '@tarojs/components'
import './index.less'
import Taro from '@tarojs/taro'
import { useEffect, useState } from 'react';
import { fetchProductsUrl } from '../../constans'



interface Product {
  id: string,
  name: string,
  price: number,
  stock: number,
}


export default function Index() {

  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  
  const fetchProducts = async () => {
      setLoading(true)
      const res = await Taro.request({
        url: fetchProductsUrl,
        method: 'GET',
        header: {
          'Content-Type': 'application/json'
        }
      })
      setProducts(res.data.info as Product[]);
      setLoading(false)
  }

  useEffect(() => {
    fetchProducts()
  }, [])


  const handleSelectProduct = (product: Product) => {
    Taro.redirectTo({
      url: `/pages/index/confirm?productId=${product.id}&productTitle=${product.name}`
    })
  }


  return (
    <View>
      <Text>商品列表</Text>
      {
        loading ? "加载中" : (
          <View>
            {products.map(product => (
              <View key={product.id} className="product-item">
                <View className="product">
                  <View className="product-item">
                    <Text >商品名称：{product.name}</Text>
                    <Text >商品库存：{product.stock}</Text>
                    <Text>商品价格：¥{product.price.toFixed(2)}</Text>
                    <Button onClick={() => handleSelectProduct(product)}>
                      立即购买
                    </Button>
                  </View>
                </View>
              </View>
            ))}
          </View>
        )
      }
    </View>
  )
}
